// const { log } = require("debug/src/browser");
var express = require("express");
var router = express.Router();
var conn = require("../../db/db");
const formidable = require('formidable');
const config = require('../config');

const { basename } = require('path');
const { log } = require("util");



const user = {};

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});
//首页轮播图
router.get("/api/homecasual", function (req, res) {
  let sql = "select * from homecasual";
  conn.query(sql, (err, result) => {
    if (err) {
      res.send({
        data: {
          code: 0,
          msg: "获取轮播图失败",
        },
      });
    } else {
      res.send({
        data: {
          code: 200,
          msg: result,
        },
      });
    }
  });
});
//首页分类
router.get("/api/category", function (req, res) {
  let sql = "select * from category";
  conn.query(sql, (err, result) => {
    if (err) {
      res.send({
        code: 0,
        msg: "获取失败",
      });
    } else {
      res.send({
        code: 200,
        msg: result,
      });
    }
  });
});
//首页分类
router.get("/api/homeshoplist", (req, res) => {
  // 获取总分类
  let cateSqlStr = "SELECT COUNT(*) FROM category";
  conn.query(cateSqlStr, (error, results, fields) => {
    if (!error) {
      let sqlStr = "";
      for (let i = 0; i < results[0]["COUNT(*)"]; i++) {
        //  sqlStr +='SELECT * FROM recommend WHERE category ='+(i+1) +' LIMIT 3;';
        sqlStr +=
          "SELECT * FROM recommend WHERE category = " + (i + 1) + " LIMIT 3;";
      }
      conn.query(sqlStr, (error, results, fields) => {
        if (!error) {
          results = JSON.parse(JSON.stringify(results));
          res.send({ success_code: 200, message: results });
        }
      });
    }
  });
});
//用户注册发送验证码
router.get("/api/send_code", (req, res) => {
  let iphone = req.query.phone;
  let rule = /^1[23456789]\d{9}$/;
  if (rule.test(iphone)) {
    let min = 100000; //最小值
    let max = 999999; //最大值
    let range = max - min; //取值范围差
    let random = Math.random(); //小于1的随机数
    let result = min + Math.round(random * range); //最小数加随机数*范围差

    setTimeout(() => {
      user[iphone] = result;

      res.send({
        code: 200,
        msg: result,
      });
    }, 2000);
  } else {
    res.send({
      code: 0,
      msg: "获取失败",
    });
  }
});
//验证码登录
router.post("/api/login_code", (req, res) => {
  const phone = req.body.phone;
  const codeinfo = req.body.code;

  if (user[phone] != codeinfo) {
    res.send({
      code: 0,
      msg: "验证码不正确",
    });
    return;
  }
  delete user[phone];
  //查询数据库
  let sql =
    "select * from user_info where user_phone = '" + phone + "' limit 1";
  conn.query(sql, (err, resu) => {
    if (err) {
      console.log("查询失败");
    } else {
      resu = JSON.parse(JSON.stringify(resu));
      if (resu[0]) {
       
        req.session.userId = resu[0].id;
        res.send({
          code: 200,
          msg: {
            id: resu[0].id,
            user_name: resu[0].user_name,
            user_nickname: resu[0].user_nickname || "",
            user_phone: resu[0].user_phone,
            user_sex: resu[0].user_sex,
            user_address: resu[0].user_address,
            user_sign: resu[0].user_sign,
            user_birthday: resu[0].user_birthday,
          },
        });
      } else {
        //新用户
        const addsql =
          "insert into user_info(user_phone, user_pwd) values (?, ?)";
        const addsqls = [phone, phone];
        conn.query(addsql, addsqls, (e, r) => {
          r = JSON.parse(JSON.stringify(r));

          if (!e) {

            req.session.userId = r.insertId;

            let sqlstr =
              "select * from user_info where id ='" + r.insertId + "' limit 1";
            conn.query(sqlstr, (error, results) => {
              if (error) {
                res.send({ code: 0, msg: "注册失败" });
              } else {
                results = JSON.parse(JSON.stringify(results));
                res.send({
                  code: 200,
                  msg: {
                    id: results[0].id,
                    user_name: results[0].user_name,
                    user_phone: results[0].user_phone,
                  },
                });
              }
            });
          }
        });
      }
    }
  });


});
//密码登录
router.post("/api/login_pwd", function (req, res) {
  let name = req.body.zh;
  let pwd = req.body.mm;
  let sql =
    "select * from user_info where user_phone = '" +
    name +
    "' and user_pwd = '" +
    pwd +
    "' limit 1";
  conn.query(sql, (err, ress) => {
    if (err) {
      res.send({
        code: 0,
      });
      
    } else {
      if (ress[0]) {
        if (ress[0].user_pwd != pwd) {
          res.send({
            code: 0,
            msg: "密码错误",
          });
        } else {
          ress = JSON.parse(JSON.stringify(ress));
          if (ress[0]) req.session.userId = ress[0].id;
          res.send({
            code: 200,
            msg: {
              id: ress[0].id,
              user_name: ress[0].user_name || "",
              user_nickname: ress[0].user_nickname || "",
              user_phone: ress[0].user_phone || "",
              user_sex: ress[0].user_sex || "",
              user_address: ress[0].user_address || "",
              user_sign: ress[0].user_sign || "",
              user_birthday: ress[0].user_birthday || "",
            },
            info: "登录成功",
          });
        }
      }
      else {
        res.send({
          code: 0,
          msg:"账号或密码错误"
        });
      }
    }
  });
});
// 根据id获取用户信息
router.get("/api/userinfo", function (req, res) {

  let userid=req.query.user_id ||req.session.userId;
  

  let sql="select * from user_info where id = " + userid + " limit 1";
  conn.query(sql,(e,r)=>{
    if(e){
      console.log(e);
      res.send({
        code:0,
        msg:"请求数据失败"
      })
    }else{
      r=JSON.parse(JSON.stringify(r))
      if(!r[0]){
        delete req.session.userId;
        res.send({
          code:0,
          msg:"请先登录"
        })
      }else{
        res.send({
          code:200,
          msg:{
            id: r[0].id,
            user_name: r[0].user_name || '',
            user_nickname: r[0].user_nickname || '',
            user_phone: r[0].user_phone || '',
            user_sex: r[0].user_sex || '',
            user_address: r[0].user_address || '',
            user_sign: r[0].user_sign || '',
            user_birthday: r[0].user_birthday || '',

          }
        })
      }
    }
  })

  
});


//退出登录
router.get("/api/logout", function (req, res, ) {
delete req.session.userId
res.send({
  code:200,
  msg:"退出登录成功"
})
});
//获取商品详情
router.get("/api/detail", function (req, res,) {
let id=req.query.id
let sql="select * from recommend where goods_id =" + id  ;
 conn.query(sql,(e,r)=>{
  if(!e){
    r=JSON.parse(JSON.stringify(r))
    res.send({
      code:200,
      msg:r
    })

  }
 })
});
//获取商品详情的评论
router.get("/api/comment", function (req, res, ) {
  let goodid=req.query.id
  let sql="select user_info.id, user_info.user_name, user_info.user_nickname, comments.comment_detail, comments.comment_id,comments.comment_rating, comments.goods_id from user_info inner join comments on user_info.id = comments.user_id where goods_id = " + goodid;
conn.query(sql,(e,r)=>{
  if(!e){
    r=JSON.parse(JSON.stringify(r))
    res.send({
      code:200,
      msg:r
    })
  }

})

});
//发布评论
router.post("/api/postcomment",function (req, res) {

  let id=req.body.id//商品id
  let comment=req.body.comment//发布评论
  let rating=req.body.rating//评论的星星
  let  uid=req.body.uid//用户id
 
  let sql="insert into comments(goods_id,comment_detail,comment_rating,user_id) value(?,?,?,?)";
  let addsql=[id,comment,rating,uid];
  conn.query(sql,addsql,(e,r)=>{
    r=JSON.parse(JSON.stringify(r));
    if(!e){
      let sqls="update recommend set comments_count = comments_count + 1 where goods_id="+id
    conn.query(sqls,(err,reu)=>{
      if(err){
        console.log(err);
      }else{
        res.send({
          code:200,
          msg:"发布成功"

        })
      }
    })
    
    }
  })


  
});
// 获取推荐商品数据
router.get("/api/recommendshoplish", function (req, res) {
let category=req.query.category || 1;
let pageno=req.query.pageno || 1;
let pagesize =req.query.count || 3;

let sql='SELECT * FROM recommend WHERE category = ' + category + ' LIMIT ' + (pageno - 1) * pagesize + ',' + pagesize;
conn.query(sql,(e,r)=>{
  if(e){
    res.send({
      code:0,
      msg:"获取失败"
    })
  }else{
    r=JSON.parse(JSON.stringify(r));  
    res.send({
      code:200,
      msg:r
    })
  }
})

});
//模糊查询
router.post("/api/searchgood", function (req, res, ) {
let keyword=req.body.keyword||{};
let sql='select * from recommend where goods_name like'+"'%" + keyword + "%'";
conn.query(sql,(e,r)=>{
  console.log(r);
  r=JSON.parse(JSON.stringify(r));
  if(!e && r.length){
    res.send({
      code:200,
      msg:r
    })
  }else{
    res.send({
      code:0,
      msg:[]
    })
  }
})

});
//添加到购物车
router.post("/api/addcart", function (req, res) {

 let user_id=req.body.user_id||{};
 let goods_id=req.body.goods_id||{};
 let goods_name=req.body.goods_name||{};
 let  thumb_url=req.body.thumb_url||{};
 let  price=req.body.price ||{};
 let buy_count=req.body.buy_count||{};
 let counts=req.body.counts||{};
 let pay=0//0是没购买，1是购买
if(!user_id){
  res.send({
    code:1,
    msg:"请先登录"
  })
  return;
}
let sql = "select * from cart where goods_id = " + goods_id + " and user_id=" + user_id + " limit 1";
conn.query(sql,(e,r)=>{
if(e){
  res.send({
    code:0,
    msg:"添加失败"
  })
}else{
  r=JSON.parse(JSON.stringify(r));
  if(r[0]){
    res.send({
      code:200,
      msg:"已存在"
  })
}else{
  let sqlarr="INSERT INTO cart(goods_id, goods_name, thumb_url, price, buy_count, is_pay, user_id, counts) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
  let sqlparmas=[goods_id,goods_name,thumb_url,price,buy_count,pay,user_id,counts];
  conn.query(sqlarr,sqlparmas,(ee,rr)=>{
    if(e){
      res.send({
        code:0,
        msg:"添加失败"
      })
    }else{
      res.send({
        code:200,
        msg:"添加成功"
      })
    }



  })

}
}
})


});
//查询购物车商品
router.get("/api/cartgoods", function (req, res, next) {
  let user_id=req.query.user_id||{};

let sql="select * from cart where user_id="+user_id;
conn.query(sql,(e,r)=>{
  if(e){
    res.send({
      code:0,
      msg:"查询失败"
    })
  }else{
    r=JSON.parse(JSON.stringify(r));
    res.send({
      code:200,
      msg:r,
     
    })
  }
})
  
});
//修改购物车商品的数量
router.post("/api/change_goods_count", function (req, res) {

 const goods_id=req.body.goods.goods_id||{};
 const num=req.body.num||{};
 const user_id=req.body.user_id||{};
 let sql= "UPDATE cart SET buy_count = ? WHERE goods_id = " + goods_id + " AND user_id = " + user_id;
 let sqlpara=[num];
 conn.query(sql,sqlpara,(e,r)=>{
  
  if(e){
    
    res.send({
      code:0,
      msg:"修改失败"
    })
  }else{
    r=JSON.parse(JSON.stringify(r));
    res.send({
      code:200,
      msg:"修改成功"
    })
  }
 })
});
//删除单个商品
router.post("/api/delete_goods", function (req, res) {
  let goods_id=req.body.goods_id.goods_id ||{};
  let user_id=req.body.user_id ||{};
let sql="delete from cart where goods_id = " + goods_id + " and user_id = " + user_id;
 conn.query(sql,(e,r)=>{
  if(e){
    
    res.send({
      code:0,
      msg:"删除失败"
    })
  }else{
    res.send({
      code:200,
      msg:"删除成功"
    })
  }
 })
});
//删除全部商品
router.post("/api/delete_goods_all", function (req, res, next) {
  let user_id=req.body.user_id ||{};
  let sql="delete from cart where user_id = " + user_id;
  conn.query(sql,(e,r)=>{
    if(e){
      res.send({
        code:0,
        msg:"删除失败"
      })
    }else{
      res.send({
        code:200,
        msg:"删除成功"
      })
    }
  })
});
//批量删除
router.post("/api/pldelete", function (req, res, next) {
  let goods_i=req.body.id ||{}
  let good=req.body.a ||{}
  let promises=[];
 
  for(let i=0;i<good.length;i++){  
    let prom=new Promise((e,r)=>{
      let sql="delete from cart where goods_id = " + good[i].goods_id   +  " and user_id = " + goods_i ;
conn.query(sql,(ee,rr)=>{
  if(ee){
    console.log(ee);
  r(err)
  }else{
    e(rr)
  }
})

    })
    promises.push(prom)

  }
Promise.all(promises).then(()=>{
  res.send({
    code:200,
    msg:"删除成功"
  })
}).catch(()=>{
  res.send({
    code:0,
    msg:"删除失败"
  })
})
 


});
//修改用户信息
router.post("/api/changeuserinfo", function (req, res, next) {
let id=req.body.id ||{};
let nickname=req.body.nickname ||{};
let sign=req.body.sign ||{};
let birthdy=req.body.birthday ||{};
let sex=req.body.sex ||{};
let sql="update user_info set user_nickname = ?,user_sign=?,user_birthday=?,user_sex=? where id = "+id;
let params=[nickname,sign,birthdy,sex];
conn.query(sql,params,(e,r)=>{
  if(e){
    console.log(e);
    res.send({
      code:0,
      msg:"修改失败"
    })
}
else{
  res.send({
    code:200,
    msg:"修改成功"
  })
}
})

});
//修改密码
router.post("/api/changeuserpwd", function (req, res, next) {
  let id=req.body.id ||{}
  let lodpwd=req.body.lowpad ||{}
  let newpwd=req.body.newpwd ||{}
  console.log(id,lodpwd,newpwd);
  let sql='select * from user_info where id = '+id;
  conn.query(sql,(e,r)=>{
    if(e){
      console.log(e);
      res.send({
        code:0,
        msg:"查询失败"
      }
      )
        }else{
          r=JSON.parse(JSON.stringify(r));
          if(r[0]){
            if(!r[0].user_pwd||(r[0].user_pwd&& lodpwd===r[0].user_pwd)){
              let sql='update user_info set user_pwd = ? where id = '+id;
              conn.query(sql,[newpwd],(e,r)=>{
                if(!e){
                  res.send({
                    code:200,
                    msg:"修改成功"
                  })
                }
              })
            }else if(lodpwd!==r[0].user_pwd){
              res.send({
                code:0,
                msg:"原密码错误",
                stat:true
              })
            }else{
              res.send({
                code:0,
                msg:"非法用户"
              })
            }
          }
        }
  })
 
});
//管理员登录
router.post("/api/adminlogin", function (req, res, ) {
  let zh=req.body.zhh ||{}
  let mm= req.body.mmm ||{}

  let sql='select * from administrators where account = '+ zh ;
  conn.query(sql,(e,r)=>{
    if(e){
    
      console.log(e);
      res.send({
        code:0,
        msg:"账号或者密码错误"
      }
      
      )
   
    }else if(r[0]){
      let user=JSON.parse(JSON.stringify(r[0]));
      
      if(mm==user['pwd']){

        req.session.adminid=user['id'];
        res.send({
          code:200,
          msg:"登录成功",
        })
      }else{
        res.send({
          code:0,
          msg:"密码错误"})
      }
    }else{
      res.send({
        code:0,
        msg:"账号不存在"
      })
    }
  })

  
});
//查询所有商品
router.get("/api/allgoods", function (req, res, next) {
 let sql="select * from recommend";
 conn.query(sql,(e,r)=>{
  if(e){

    console.log(e);
    res.send({
      code:0,
      msg:"查询失败"
    })
  }else{
    r=JSON.parse(JSON.stringify(r));
    res.send({
      code:200,
      msg:r,
    })
  }
 })
});

//修改商品信息
router.post("/api/changedgoods", function (req, res, next) {
  let id=req.body.id;
  let name=req.body.name;
  let price=req.body.price*100;
  let knum=req.body.knum;
  let gcontent=req.body.gcontent;

  let sql="UPDATE recommend SET goods_name = ?, short_name = ?, price = ?, counts = ? WHERE goods_id = " + id;
  let pasql =[name,gcontent,price,knum]
  conn.query(sql,pasql,(e,r)=>{
    if(e){
      console.log(e);
      res.send({
        code:0,
        msg:"修改失败"
      })
    }else{
      res.send({
        code:200,
        msg:"修改成功"
      })
    }
    
  })
});


//删除商品（后台）
router.post("/api/deletegoods", function (req, res, next) {
  
  let id=req.body.id;
  let sql="DELETE FROM recommend WHERE goods_id = " + id;
  conn.query(sql,(e,r)=>{
    if(e){
      console.log(e);
      res.send({
        code:0,
        msg:"删除失败"
      }
    )}
    else{
      let sql2="DELETE FROM cart WHERE goods_id = " + id;
      conn.query(sql2,(e,r)=>{
        if(e){
          console.log(e);
          res.send({
            code:0,
            msg:"删除失败"
          }
        )
              } 
        else{
          res.send({
            code:200,
            msg:"删除成功"
          } 
        )
              }
      }
      )
      
  }
  })
 

});
//商品上架

router.post("/api/addgoodrecom", function (req, res, next) {
  const form = new formidable.IncomingForm();
  form.uploadDir = config.uploadsGoodsPath;//图片上传的文件夹
  form.keepExtensions = true;//保持文件的原始扩展名
  
  form.parse(req,(err, fields, files) => {
    
    if(err){
      return next(err);
    }

    let gid=fields.gid;
  let gname=fields.gname;
  let gprice=fields.price*100;
  let normal_price = fields.price + 99;
  let market_price = fields.price + 99;
  let gknum=fields.knum;
  let cag=fields.types;
  let detail=fields.detail;
  let comments_count = 0;
  
 
  let thumb_url = 'http://localhost:' + config.port + '/uploads/' + basename(files.good_img.path);
  let image_url = 'http://localhost:' + config.port + '/uploads/' + basename(files.good_img.path);
  let hd_thumb_url = 'http://localhost:' + config.port + '/uploads/' + basename(files.good_img.path);

let sql='select * from recommend where goods_id = '+gid;
conn.query(sql,(e,r)=>{
  if(e){
    console.log(e);
    res.send({
      code:0,
      msg:"添加失败"  
                }
            )
  }else{
    //有商品
    r=JSON.parse(JSON.stringify(r));
    if(r[0]){
      res.send({
        code:500,
        msg:"已经在数据库"
                }
            )
    }else{
      //没有有商品
      let  addsql="INSERT INTO recommend(goods_id, goods_name, short_name, thumb_url, image_url, hd_thumb_url, price, normal_price, market_price, sales_tip, category, counts, comments_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
      let sql_params = [gid, gname, detail, thumb_url, image_url, hd_thumb_url, gprice, normal_price, market_price, gknum, cag, gknum, comments_count];
   
   conn.query(addsql,sql_params,(e,r)=>{
     if(e){
       console.log(e);
       res.send({
         code:0,
         msg:"添加失败"  
                    } 
                )
     }
     else{
      let sqlStr = "UPDATE category SET cate_counts = cate_counts + 1  WHERE cate_id = " + gknum;
      conn.query(sqlStr,[],(e,r)=>{
        if(e){
          console.log(e);
          res.send({
            code:0,
            msg:"添加失败"
          })
        }else{
          res.send({
            code:200,
            msg:"添加成功"
          })
        }
      })
   
                    }
   })
    }

  }
})
  })
});
//获取所有用户
router.get("/api/alluser", function (req, res, next) {
  
  let sqlStr = 'SELECT id, user_name, user_phone, user_nickname FROM user_info';
conn.query(sqlStr, (e,r)=>{
if(e){
  console.log(e);
  res.send({
    code:0,
    msg:"获取失败"
  }
  )
}
else{
  console.log(11);
  r=JSON.parse(JSON.stringify(r));
  console.log(r);
  res.send({
    code:200,
    msg:r,
   
  })
}
})
});















module.exports = router;
